import { login, logout, userInfo } from '@/api/user'
import { getCookie, setCookie, removeCookie } from '@/utils/auth'
import i18n from '@/i18n'


// console.log("----mall getCookie('user')", getCookie('user'));

// const user = {
const state = {
  token: getCookie('token') || '',
  user: getCookie('authorization') ? JSON.parse(getCookie('authorization')) : {},
  order: {},
  shifu: {},
  xiaoxi: 0,
  tixian: 0
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_AUTHORIZATION: (state, authorization) => {
    state.authorization = authorization
  },
  SET_ORDER: (state, ordernum) => {
    state.order = ordernum
  },
  SET_SHIFU: (state, shifu) => {
    state.shifu = shifu
  },
  SET_XIAOXI: (state, xiaoxi) => {
    state.xiaoxi = xiaoxi
  },
  SET_TIXIAN: (state, tixian) => {
    state.tixian = tixian
  },
}

//   actions: {
//     // 登录
//     login({ commit }, params) {
//       console.log(params)
//       return new Promise((resolve, reject) => {
//         login(params).then(res => {
//           console.log(res)
//           // setCookie('md5_secretkey', params.password)
//           setCookie('token', res.data.token)
//           commit('SET_TOKEN', res.data.token)
//           localStorage.setItem("authorization", res.data.authorization);
//           // localStorage.setItem('usersInfo', JSON.stringify(data.info))
//           resolve()
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },

//     // 用户信息
//     UserInfo({ commit }, params) {
//       return new Promise((resolve, reject) => {
//         userInfo(params).then(res => {
//           localStorage.setItem('user', JSON.stringify(res.data));
//           setCookie('user', res.data)
//           commit('SET_USER', res.data)
//           resolve()
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },

//     // 退出系统
//     LogOut({ commit, state }) {
//       return new Promise((resolve, reject) => {
//         logout().then(() => {
//           localStorage.clear();
//           removeCookie('md5_secretkey')
//           removeCookie('user')
//           removeCookie('tid')
//           removeCookie('token')
//           commit('SET_TOKEN', '')
//           resolve()
//         }).catch(error => {
//           reject(error)
//         })
//       })
//     },

//     // 前端 登出
//     FedLogOut({ commit }) {
//       return new Promise(resolve => {
//         localStorage.clear();
//         removeCookie('md5_secretkey')
//         removeCookie('user')
//         removeCookie('tid')
//         removeCookie('token')
//         commit('SET_TOKEN', '')
//         resolve()
//       })
//     }
//   }
// // }
const actions = {
  // 用户登陆
  login({ commit }, params) {
    return new Promise((resolve, reject) => {
      login(params).then(res => {
        console.log(res)
        // setCookie('md5_secretkey', params.password)
        setCookie('token', res.data)
        commit('SET_TOKEN', res.data)
        localStorage.setItem("authorization", res.data);
        // localStorage.setItem('usersInfo', JSON.stringify(data.info))
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    // console.log('进入获取用户信息')
    return new Promise((resolve, reject) => {
      // getInfo(state.token).then(response => {
      // const { data } = response

      // 临时写死的数据
      let res = { "code": 20000, "data": { "roles": ["admin"], "introduction": "我是一个超级管理员", "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif", "name": "" } }
      const { data } = res

      if (!JSON.parse(localStorage.getItem("usersInfo"))) {
        MessageBox.confirm(i18n.tc('message.prompt1'), i18n.tc('message.confirmLogout2'), {
          confirmButtonText: i18n.tc('message.logInAgin'),
          cancelButtonText: i18n.tc('message.cancel'),
          type: 'warning'
        }).then(() => {
          store.dispatch('user/logout').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
        // reject('Verification failed, please Login again.')
      }


      if (!data) {
        // 验证失败 请重新登录
        // console.log('获取用户信息失败,请重新登录')
        reject(i18n.tc('message.validateError'))
      }

      const { roles, name, avatar, introduction } = data

      // 角色必须是非空数组
      if (!roles || roles.length <= 0) {
        reject('getInfo: roles must be a non-null array!')
      }

      commit('SET_ROLES', roles)
      commit('SET_NAME', name)
      commit('SET_AVATAR', avatar)
      commit('SET_INTRODUCTION', introduction)
      resolve(data)
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      localStorage.clear();
      sessionStorage.clear();
      // router.push("/");
      // removeToken()
      // resetRouter()

      // // reset visited views and cached views
      // // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      // dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
  resetOrder({ commit }, status) { //刷新订单 师傅数量
    return new Promise(resolve => {
      // console.log(status)
      resolve()
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
